<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>其他费用管理</title>
    <!-- 引入其它组件 -->
    <!-- 引入 layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            padding: 20px;
            background-color: #f2f2f2;
            height: 100vh;
            overflow: hidden;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            height: calc(100vh - 40px);
            display: flex;
            flex-direction: column;
        }

        .table-container {
            flex: 1;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }

        .table-wrapper {
            flex: 1;
            overflow: auto;
            border: 1px solid #e6e6e6;
            margin-bottom: 15px;
        }

        .layui-table {
            width: 100%;
            margin-bottom: 0;
        }

        .layui-table th {
            text-align: center;
            font-weight: bold;
            background-color: #f8f8f8;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .layui-table td {
            padding: 8px 12px;
        }

        .total-row {
            font-weight: bold;
            background-color: #e6f7ff !important;
            position: sticky;
            bottom: 0;
            z-index: 10;
        }

        .manual-row {
            background-color: #f6ffed !important;
        }

        .delete-btn {
            cursor: pointer;
        }

        .loading-mask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .button-container {
            flex-shrink: 0;
            padding-top: 15px;
            border-top: 1px solid #f0f0f0;
            text-align: center;
        }

        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .status-saved {
            background-color: #5FB878;
        }

        .status-unsaved {
            background-color: #FF5722;
        }

        /* 弹出窗口专用样式 */
        .dialog-input-group {
            display: flex;
            align-items: center;
            margin-bottom: 18px;
            min-height: 36px;
        }

        .dialog-input-prefix {
            width: 80px;
            padding-right: 12px;
            text-align: right;
            font-weight: bold;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .dialog-input-content {
            flex: 1;
            display: flex;
            align-items: center;
        }

        .input-with-unit {
            display: flex;
            align-items: center;
            flex: 1;
        }

        .input-with-unit input {
            flex: 1;
        }

        .input-with-unit .unit {
            width: 60px;
            padding-left: 10px;
            white-space: nowrap;
        }

        .dialog-textarea-group {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
        }

        .dialog-textarea-prefix {
            width: 80px;
            padding-right: 12px;
            text-align: right;
            font-weight: bold;
            white-space: nowrap;
            flex-shrink: 0;
            padding-top: 8px;
        }

        .dialog-textarea-content {
            flex: 1;
        }
    </style>
</head>

<body>
    <div class="container" id="main-container">
        <!-- 加载遮罩层 -->
        <div class="loading-mask" id="loading-mask">
            <div class="layui-card">
                <div class="layui-card-body">
                    <i class="layui-icon layui-anim layui-anim-rotate layui-anim-loop">&#xe63d;</i>
                    <span style="margin-left: 10px;">正在加载项目数据...</span>
                </div>
            </div>
        </div>

        <div class="table-container">
            <div class="table-wrapper">
                <table class="layui-table" lay-size="sm" id="budget-table">
                    <colgroup>
                        <col width="3%">
                        <col width="20%">
                        <col width="20%">
                        <col width="8%">
                        <col width="8%">
                        <col width="8%">
                        <col width="15%">
                        <col width="6%">
                    </colgroup>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>费用名称</th>
                            <th>计算依据及方法</th>
                            <th>除税价（元）</th>
                            <th>增值税（元）</th>
                            <th>含税价（元）</th>
                            <th>备注</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="table-body">
                        <!-- 数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>

            <div class="button-container">
                <div class="layui-form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <button class="layui-btn layui-btn-normal" id="btn-add">
                                <i class="layui-icon">&#xe654;</i> 增 加
                            </button>
                            <button class="layui-btn layui-btn-normal" id="btn-save">
                                <i class="layui-icon">&#xe605;</i> 保 存
                            </button>
                            <span id="save-status" style="margin-left: 15px; color: #666; display: none;">
                                <span class="status-indicator status-saved"></span>已保存
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>

    <script>
        layui.use(['jquery', 'layer', 'form'], function () {
            var $ = layui.$;
            var layer = layui.layer;
            var form = layui.form;
            var manualRowCount = 0;
            var rateVat = 0.09;
            var rateSafe = 0.015;
            var designCode = getUrlParam("design_code");
            var designType = parseInt(getUrlParam("design_type"));

            // 状态管理变量
            var hasUnsavedChanges = false;
            var originalDataHash = "";

            // 表格数据
            var tableData = {
                staticRows: [],
                totalRow: [],
                manualRows: []
            };
            var totalResult = { totalTaxExcluded: 0, totalTax: 0, totalTaxIncluded: 0 };

            initPage();

            function initPage() {
                try {
                    // 后端获取总安装费（不含税）
                    http.get(API_CONFIG.ENDPOINTS.LOAD_OTHER_FEE, {
                        design_code: designCode,
                        design_type: designType
                    }).then(function (res) {
                        if (res.code === 0) {
                            const constructionCost = Number(res.data.construction_cost);
                            // 安全系数
                            rateSafe = Number(res.data.rate_safe);
                            // 增值税系数
                            rateVat = Number(res.data.rate_vat);

                            // 生成表格数据
                            generateTableData(constructionCost, res.data.other_fee);

                            // 隐藏加载遮罩
                            $('#loading-mask').hide();

                            // 初始加载后标记为已保存
                            markAsSaved();
                        }
                    });
                }
                catch (error) {
                    console.error("获取总安装费失败:", error);
                }

                // 添加行按钮点击事件
                $(document).on('click', '#btn-add', function () {
                    showAddRowDialog();
                });

                // 绑定删除事件（使用事件委托）
                $(document).on('click', '.delete-btn', function () {
                    var id = $(this).data('id');
                    layer.confirm('确定要删除此行吗？', function (index) {
                        // 从数据中移除
                        tableData.manualRows = tableData.manualRows.filter(item => item.id !== id);

                        // 重新渲染表格
                        renderTable();
                        markAsUnsaved(); // 标记有未保存的更改
                        layer.close(index);
                    });
                });
            }

            // 生成数据哈希用于比较数据变化
            function generateDataHash(data) {
                return JSON.stringify(data.map(item => ({
                    name: item.name,
                    basis: item.basis,
                    taxIncluded: item.taxIncluded,
                    remark: item.remark
                })));
            }

            // 检查是否有未保存的更改
            window.hasUnsavedChanges = function () {
                return hasUnsavedChanges;
            };

            // 更新保存状态显示
            function updateSaveStatus() {
                var $status = $('#save-status');
                if (hasUnsavedChanges) {
                    $status.show().find('.status-indicator')
                        .removeClass('status-saved')
                        .addClass('status-unsaved')
                        .next('span').text('未保存');
                } else {
                    $status.show().find('.status-indicator')
                        .removeClass('status-unsaved')
                        .addClass('status-saved')
                        .next('span').text('已保存');
                }
            }

            // 标记有未保存的更改
            function markAsUnsaved() {
                var currentHash = generateDataHash(tableData.manualRows);
                hasUnsavedChanges = (currentHash !== originalDataHash);
                updateSaveStatus();
            }

            // 标记为已保存
            function markAsSaved() {
                originalDataHash = generateDataHash(tableData.manualRows);
                hasUnsavedChanges = false;
                updateSaveStatus();
            }

            // 生成表格数据
            function generateTableData(constructionCost, otherFee) {
                // 计算安全生产费（建筑安装工程费×2.00%）
                console.log("安装费合计:", constructionCost);

                var safetyProductionCost = constructionCost * rateSafe;
                var safetyProductionTax = safetyProductionCost * rateVat;
                var safetyProductionTotal = safetyProductionCost + safetyProductionTax;

                // 静态数据行
                tableData.staticRows = [
                    { id: 1, name: '建设用地及综合赔补费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 2, name: '建设单位管理费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 3, name: '可行性研究费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 4, name: '研究试验费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 5, name: '勘察设计费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 5.1, name: '其中：勘察费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 5.2, name: '其中：设计费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 6, name: '环境影响评价费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 7, name: '劳动安全卫生评价费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 8, name: '建设工程监理费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 9, name: '安全生产费', basis: `建筑安装工程费×${(rateSafe * 100).toFixed(2)}%`, taxExcluded: safetyProductionCost, tax: safetyProductionTax, taxIncluded: safetyProductionTotal, remark: `建筑安装工程费: ${constructionCost.toFixed(2)}元`, isManual: false },
                    { id: 10, name: '工程质量监督费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 11, name: '工程定额测定费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 12, name: '引进技术及引进设备其它费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 13, name: '工程保险费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 14, name: '工程招标代理费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false },
                    { id: 15, name: '专利及专利技术使用费', basis: '', taxExcluded: 0, tax: 0, taxIncluded: 0, remark: '', isManual: false }
                ];

                // 初始化总计行
                tableData.totalRow = [
                    {
                        id: '',
                        name: '总计',
                        basis: '',
                        taxExcluded: totalResult.totalTaxExcluded.toFixed(2),
                        tax: totalResult.totalTax.toFixed(2),
                        taxIncluded: totalResult.totalTaxIncluded.toFixed(2),
                        remark: '',
                        isManual: false
                    }
                ];

                // 初始化手动行为空
                tableData.manualRows = [];
                var otherArray = (otherFee && Array.isArray(otherFee)) ? otherFee : [];
                for (let i = 0; i < otherArray.length; i++) {
                    const element = otherArray[i];
                    var taxIncluded = Number(element.tax_included);
                    var taxExcluded = taxIncluded / (1 + rateVat);
                    var tax = taxIncluded - taxExcluded;
                    addManualRow(element.name, element.basis, taxExcluded, tax, taxIncluded, element.remark);
                }

                // 渲染表格
                renderTable();
            }

            // 渲染表格
            function renderTable() {
                var tableBody = $('#table-body');
                tableBody.empty();

                // 添加静态行
                tableData.staticRows.forEach(row => {
                    var isSubItem = row.id.toString().includes('.');
                    var rowHtml = `
                        <tr${isSubItem ? ' style="background-color: #f9f9f9;"' : ''}>
                            <td>${isSubItem ? '' : Math.floor(row.id)}</td>
                            <td>${row.name}</td>
                            <td>${row.basis}</td>
                            <td style="text-align: right;">${row.taxExcluded.toFixed(2)}</td>
                            <td style="text-align: right;">${row.tax.toFixed(2)}</td>
                            <td style="text-align: right;">${row.taxIncluded.toFixed(2)}</td>
                            <td>${row.remark}</td>
                            <td></td>
                        </tr>
                    `;
                    tableBody.append(rowHtml);
                });

                // 计算总计
                calculateTotal();

                // 添加总计行
                tableData.totalRow.forEach(row => {
                    var rowHtml = `
                        <tr class="total-row" data-id="${row.id}">
                        <td></td>
                        <td>${row.name}</td>
                        <td>${row.basis}</td>
                        <td style="text-align: right;">${totalResult.totalTaxExcluded.toFixed(2)}</td>
                        <td style="text-align: right;">${totalResult.totalTax.toFixed(2)}</td>
                        <td style="text-align: right;">${totalResult.totalTaxIncluded.toFixed(2)}</td>
                        <td>${row.remark}</td>
                        <td></td>
                    </tr>
                    `;
                    console.log(rowHtml)
                    tableBody.append(rowHtml)
                });

                // 添加手动行
                tableData.manualRows.forEach(row => {
                    var rowHtml = `
                        <tr class="manual-row" data-id="${row.id}">
                            <td>${16 + tableData.manualRows.indexOf(row)}</td>
                            <td>${row.name}</td>
                            <td>${row.basis}</td>
                            <td style="text-align: right;">${row.taxExcluded.toFixed(2)}</td>
                            <td style="text-align: right;">${row.tax.toFixed(2)}</td>
                            <td style="text-align: right;">${row.taxIncluded.toFixed(2)}</td>
                            <td>${row.remark}</td>
                            <td>
                                <button class="layui-btn layui-btn-danger layui-btn-xs delete-btn" data-id="${row.id}">删除</button>
                            </td>
                        </tr>
                    `;
                    tableBody.append(rowHtml);
                });

                form.render();
            }

            // 计算总计
            function calculateTotal() {
                totalResult.totalTaxExcluded = 0;
                totalResult.totalTax = 0;
                totalResult.totalTaxIncluded = 0;

                // 计算静态行
                tableData.staticRows.forEach(row => {
                    totalResult.totalTaxExcluded += row.taxExcluded;
                    totalResult.totalTax += row.tax;
                    totalResult.totalTaxIncluded += row.taxIncluded;
                });

                // 计算手动行
                tableData.manualRows.forEach(row => {
                    totalResult.totalTaxExcluded += row.taxExcluded;
                    totalResult.totalTax += row.tax;
                    totalResult.totalTaxIncluded += row.taxIncluded;
                });
            }

            // 显示添加行的对话框
            function showAddRowDialog() {
                layer.open({
                    type: 1,
                    title: "添加费用项目",
                    content: `
                    <div class="layui-form" style="padding-right: 20px;padding-top: 20px;">
                        <div class="dialog-input-group">
                            <div class="dialog-input-prefix">费用名称</div>
                            <div class="dialog-input-content">
                                <input type="text" class="layui-input" id="fee-name" placeholder="请输入费用名称">
                            </div>
                        </div>
                        
                        <div class="dialog-input-group">
                            <div class="dialog-input-prefix">计算依据</div>
                            <div class="dialog-input-content">
                                <input type="text" class="layui-input" id="fee-basis" placeholder="请输入计算依据及方法">
                            </div>
                        </div>
                        
                        <div class="dialog-input-group">
                            <div class="dialog-input-prefix">含税金额</div>
                            <div class="dialog-input-content">
                                <div class="input-with-unit">
                                    <input type="number" class="layui-input" id="fee-tax-included" placeholder="0.00" step="0.01" min="0">
                                    <div class="unit">元</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="dialog-textarea-group">
                            <div class="dialog-textarea-prefix">备注说明</div>
                            <div class="dialog-textarea-content">
                                <textarea class="layui-textarea" id="fee-remark" placeholder="请输入备注信息" style="min-height: 60px;"></textarea>
                            </div>
                        </div>
                    </div>`,
                    btn: ['确认', '取消'],
                    btnAlign: 'c',
                    area: ['500px', '380px'],
                    success: function (layero, index) {
                        this.layero = layero;
                        layero.find('#fee-name').focus();

                        // 绑定回车键确认
                        layero.find('input').on('keypress', function (e) {
                            if (e.keyCode === 13) $('.layui-layer-btn0').click();
                        });
                    },
                    yes: function (index) {
                        var layero = this.layero;
                        var feeName = $('#fee-name', layero).val().trim();
                        var feeBasis = $('#fee-basis', layero).val().trim();
                        var taxIncluded = parseFloat($('#fee-tax-included', layero).val()) || 0;
                        var feeRemark = $('#fee-remark', layero).val().trim();

                        // 验证输入
                        if (!feeName) {
                            layer.msg('请输入费用名称', { icon: 2 });
                            $('#fee-name', layero).focus();
                            return false;
                        }

                        if (taxIncluded <= 0) {
                            layer.msg('请输入有效的金额', { icon: 2 });
                            $('#fee-tax-included', layero).focus();
                            return false;
                        }

                        // 计算除税价和增值税
                        var taxExcluded = taxIncluded / (1 + rateVat);
                        var tax = taxIncluded - taxExcluded;

                        // 添加新行
                        addManualRow(feeName, feeBasis, taxExcluded, tax, taxIncluded, feeRemark);
                        layer.close(index);
                    }
                });
            }

            // 添加手动行到表格
            function addManualRow(name, basis, taxExcluded, tax, taxIncluded, remark) {
                manualRowCount++;

                var newRow = {
                    id: 'manual_' + manualRowCount,
                    name: name,
                    basis: basis,
                    taxExcluded: taxExcluded,
                    tax: tax,
                    taxIncluded: taxIncluded,
                    remark: remark,
                    isManual: true
                };

                // 添加到数据中
                tableData.manualRows.push(newRow);

                // 重新渲染表格
                renderTable();

                // 标记有未保存的更改
                markAsUnsaved();
            }

            // 保存数据函数（暴露给父窗口）
            window.saveData = function (callback) {
                // 收集数据
                var saveData = tableData.manualRows.map(function (item) {
                    return {
                        design_code: designCode,
                        design_type: designType,
                        name: item.name,
                        basis: item.basis,
                        tax_included: item.taxIncluded,
                        remark: item.remark,
                    }
                });

                // 发送请求
                http.post(API_CONFIG.ENDPOINTS.SAVE_OTHER_FEE, {
                    design_code: designCode,
                    design_type: designType,
                    other_table: saveData,
                }).then(function (res) {
                    if (res.code === 0) {
                        layer.msg('保存成功', { icon: 1 });
                        markAsSaved(); // 标记为已保存
                        // 刷新父页面项目摘要数据
                        if (parent && parent.updateProjectData) {
                            parent.updateProjectData(designCode, designType);
                        }

                        if (typeof callback === 'function') callback(true);
                    } else {
                        layer.msg(res.msg || '保存失败，请重试', { icon: 2 });
                        if (typeof callback === 'function') callback(false);
                    }
                }).catch(function (err) {
                    layer.msg('网络错误，保存失败', { icon: 2 });
                    if (typeof callback === 'function') callback(false);
                });
            };

            // 保存按钮点击事件
            $('#btn-save').click(function () {
                window.saveData(function (success) {
                    if (success) {
                        // 保存成功后的额外操作
                    }
                });
            });

            // 工具函数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                return r ? decodeURIComponent(r[2]) : null;
            }

            // 添加页面离开前的提示
            window.addEventListener('beforeunload', function (e) {
                if (hasUnsavedChanges) {
                    var confirmationMessage = '您有未保存的更改，确定要离开吗？';
                    e.returnValue = confirmationMessage;
                    return confirmationMessage;
                }
            });
        });
    </script>
</body>

</html>